﻿using AutoMapper;
using TxtManager.Application.DTOs;
using TxtManager.Core;
using TxtManager.Core.Entities;
using TxtManager.Core.Interfaces;
using TxtManager.Core.Repository;

namespace TxtManager.Application.Services;

public class TextService
{
    private readonly ITextRepository _repository;

    private readonly IMapper _mapper;

    public TextService(ITextRepository repository, IMapper mapper)
    {
        _repository = repository;
        _mapper = mapper;
    }

    /// <summary>
    /// 创建文本
    /// </summary>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public async Task<TextItemDto> CreateTextItemAsync(TextItemDto model)
    {
        if (string.IsNullOrWhiteSpace(model.Title))
            throw new ArgumentException("标题不能为空");

        var textItem = _mapper.Map<TextItem>(model);

        await _repository.AddAsync(textItem);
        return _mapper.Map<TextItemDto>(textItem);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<TextItemDto> GetTextItemByIdAsync(int id)
    {
        var entity = await _repository.GetByIdAsync(id);


        return _mapper.Map<TextItemDto>(entity);
    }

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<TextItemDto>> GetAllItemsAsync()
    {
        var items = await _repository.GetAllAsync();
        return _mapper.Map<IEnumerable<TextItemDto>>(items);
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task DeleteItemAsync(int id)
    {
        var item = await _repository.GetByIdAsync(id);
        if (item == null) throw new Exception("条目不存在");

        await _repository.DeleteAsync(id);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task UpdateItemAsync(TextItemDto model)
    {
        await _repository.UpdateAsync(_mapper.Map<TextItem>(model));
    }


    public async Task<PagedResultDto<TextItemDto>> SearchItemAsync(int currentPage, int pageSize, string keyword)
    {
        var textItemEntity = await _repository.SearchByKeywordAsync(currentPage, pageSize, keyword);

        var models = _mapper.Map<IEnumerable<TextItemDto>>(textItemEntity);


        var totalCount = await _repository.CountTextItemsAsync(keyword);


        return new PagedResultDto<TextItemDto>
        {
            Items = models,
            TotalCount = totalCount,
            PageSize = pageSize,
            PageIndex = currentPage
        };

    }


}